package cn.getech.data.metadata.service.impl;

import cn.getech.data.metadata.api.gateway.model.dto.CollectionDataLevelSetting;
import cn.getech.data.metadata.api.gateway.model.dto.CollectionSetting;
import cn.getech.data.metadata.mapper.CollectionDataLevelSettingMapper;
import cn.getech.data.metadata.mapper.CollectionSettingMapper;
import cn.getech.data.metadata.model.req.setting.CollectionSettingReq;
import cn.getech.data.metadata.model.req.setting.DataLevelSettingReq;
import cn.getech.data.metadata.service.CollectionSettingService;
import cn.getech.system.center.utils.ShiroUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service("collectionSettingService")
public class CollectionSettingServiceImpl implements CollectionSettingService {
    @Autowired
    private CollectionSettingMapper collectionSettingMapper;
    @Autowired
    private CollectionDataLevelSettingMapper collectionDataLevelSettingMapper;
    @Override
    public String save(CollectionSettingReq req) {
        Long userId= ShiroUtils.getUserId();
        CollectionSetting config=req.toDto();
        Integer tenantId = ShiroUtils.getTenantId();
        config.setTenantId(tenantId);
        //获取当前系统中目录最大数
        List<Integer> current = collectionSettingMapper.getCurrentTeeLevelMax(tenantId);
        if (CollectionUtils.isNotEmpty(current) && current.size() == 2) {
            if (req.getTreeLevelMax()< current.get(0)) {
                return String.format("当前实际创建的元数据目录层级已经超过%s，请重新配置", req.getTreeLevelMax());
            }
            if (req.getCategoryLevelMax() < current.get(1)) {
                return String.format("当前实际创建的资产目录层级已经超过%s，请重新配置", req.getCategoryLevelMax());
            }
        }
        config.setUpdateUser(userId);
        config.setUpdateTime(new Date());
        QueryWrapper<CollectionSetting> pram = new QueryWrapper<CollectionSetting>()
                .eq(tenantId != null, "tenant_id", tenantId);
        List<CollectionSetting> configList = collectionSettingMapper.selectList(pram);
        if (CollectionUtils.isNotEmpty(configList)) {
            collectionSettingMapper.update(config, pram);
        } else {
            collectionSettingMapper.insert(config);
        }
        //清除旧数据
        collectionDataLevelSettingMapper.delete(new QueryWrapper<CollectionDataLevelSetting>()
                .eq("tenant_id",tenantId));
        if (CollectionUtils.isNotEmpty(req.getDataLevelSettingList())) {
            List<CollectionDataLevelSetting> list= Lists.newArrayList();
            for (DataLevelSettingReq dataLevelSettingReq : req.getDataLevelSettingList()) {
                if (CollectionUtils.isNotEmpty(dataLevelSettingReq.getGrades())) {
                    for (Integer grade : dataLevelSettingReq.getGrades()) {
                        CollectionDataLevelSetting dls=new CollectionDataLevelSetting();
                        dls.setManagerGrad(grade);
                        dls.setSecurityDataLevel(dataLevelSettingReq.getSecurityDataLevel());
                        dls.setTenantId(tenantId);
                        list.add(dls);
                    }
                }
            }
            if (CollectionUtils.isNotEmpty(list)) {
                collectionDataLevelSettingMapper.batchInsert(list);
            }
        }
        return null;
    }

    @Override
    public CollectionSettingReq info() {
        Integer tenantId = ShiroUtils.getTenantId();
        List<CollectionSetting> configList = collectionSettingMapper.selectList(new QueryWrapper<CollectionSetting>()
                .eq(tenantId != null, "tenant_id", tenantId));
        CollectionSettingReq req = new CollectionSettingReq();
        if (CollectionUtils.isNotEmpty(configList)) {
            req = new CollectionSettingReq(configList.get(0));
            List<Integer> current = collectionSettingMapper.getCurrentTeeLevelMax(tenantId);
            if (CollectionUtils.isNotEmpty(current) && current.size() == 2) {
                req.setCurrentTreeLevelMax(current.get(0));
                req.setCurrentCategoryLevelMax(current.get(1));
            }
        }
        List<DataLevelSettingReq> dataLevel = collectionSettingMapper.selectDataLevel(tenantId);
        if(CollectionUtils.isNotEmpty(dataLevel)) {
            dataLevel=dataLevel.stream().filter(i-> StringUtils.isNotEmpty(i.getName())).collect(Collectors.toList());
            for (DataLevelSettingReq dataLevelSettingReq : dataLevel) {
                List<CollectionDataLevelSetting> dataLevelList = collectionDataLevelSettingMapper.selectList(
                        new QueryWrapper<CollectionDataLevelSetting>()
                                .eq("security_data_level", dataLevelSettingReq.getSecurityDataLevel())
                                .eq(tenantId != null, "tenant_id", tenantId)
                                .orderByAsc("manager_grad"));
                if (CollectionUtils.isNotEmpty(dataLevelList)) {
                    List<Integer> grads = dataLevelList.stream().map(CollectionDataLevelSetting::getManagerGrad)
                            .collect(Collectors.toList());
                    dataLevelSettingReq.setGrades(grads);
                }
            }
        }
        req.setDataLevelSettingList(dataLevel);
        return req;
    }
}
